<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>区划列表</title>
    <link rel="stylesheet" type="text/css" href="/static/hplus/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/static/hplus/css/style.css">
    <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css">
    <link rel="stylesheet" type="text/css" href="/static/layer/skin/layer.css">
    <style type="text/css">
        .form-control {width: 220px;}
        .ttd {width: 250px;text-align: center;}
        .ttb {width: 80px;text-align: center;}
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <form action="/district/lists1" method="get">
                        <table style="width: 100%;padding: 0;border: none">
                            <tr>
                                <td class="ttd">
                                    <input type="text" name="keyword" placeholder="区划名称" class="input-sm form-control" value="{$keyword??''}" autocomplete="off">
                                </td>
                                <td class="ttb"><input type="submit" class="btn btn-sm btn-primary" value="搜索"></td>
                                <td><a href="javascript:;" id="add" class="btn btn-sm btn-success">添加</a>
                                    <a href="javascript:;" class="btn btn-sm btn-info" data-action="enableAll">批量启用</a>
                                    <a href="javascript:;" class="btn btn-sm btn-info" data-action="disableAll">批量禁用</a>
                                    <a href="javascript:;" class="btn btn-sm btn-info" data-action="delAll">批量删除</a></td>
                                <td>&nbsp;</td>
                            </tr>
                        </table>
                    </form>
                </div>
                <div class="ibox-content">
                    <table id="treeTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/javascript" src="/static/hplus/js/jquery.min.js?v={php}echo time(){/php}"></script>
<script type="text/javascript" src="/static/layer/layer.js?v={php}echo time(){/php}"></script>
<script type="text/javascript" src="/static/royui/royui.min.js?v={php}echo time(){/php}"></script>
<script type="text/javascript">
    $(function () {
        //let $data = JSON.parse('<?php echo json_encode($list); ?>');
        let r = new royui();
        r.treeTable({
            elem: '#treeTable',
            //data: $data,
            url: '/district/ajaxArea1',
            method: 'post',
            //is_cache: true,
            //total_page: true,
            checkbox: true,
            paging: true,
            pages: {$pages},
            cols: [
                {
                    field: 'name',
                    title: '区划名称',
                    style: 'width: 250px'
                },
                {
                    field: 'code',
                    title: '区划编码'
                },
                {
                    field: 'level_txt',
                    title: '区划级别'
                },
                {
                    field: 'ctime',
                    title: '添加时间'
                },
                {
                    field: 'mtime',
                    title: '修改时间'
                },
                {
                    field: 'status_txt',
                    title: '状态'
                },
                {
                    title: '操作',
                    action: [{
                        matter: 'edit',
                        url: '/district/edit',
                        area: ['500px', '600px'],
                        method: 'popup'
                    }, {matter: 'del', url: '/district/del1'}],
                    template: function ($item) {
                        let $str = ''
                        if ($item.level < 4) {
                            $str = '<a href="javascript:;" class="royui-button-a add" data-code="' + $item.code + '">添加下级区划</a>'
                            return $str;
                        } else {
                            return '';
                        }
                    },
                    site: 'after'
                }
            ],
            tree: {
                iconIndex: 0,
                primary_key: 'code'
            },
            onUpdated: function ($result, $obj) {
                $obj = $($obj).parent().parent().find('td');
                let $td1 = $obj.eq(1).find('span');
                if ($td1.find('div')) {
                    $td1.html('<div class="royui-icon-triangle-r"></div>' + $result['name'])
                } else {
                    $td1.html($result['name'])
                }
                let $now = new Date();
                let $month = $now.getMonth() + 1, $day = $now.getDate(), $hours = $now.getHours(),
                        $minitues = $now.getMinutes(), $second = $now.getSeconds();
                $month = $month < 10 ? '0' + $month : $month;
                $day = $day < 10 ? '0' + $day : $day;
                $hours = $hours < 10 ? '0' + $hours : $hours;
                $minitues = $minitues < 10 ? '0' + $minitues : $minitues;
                $second = $second < 10 ? '0' + $second : $second;
                let $td5 = $obj.eq(5).find('span');
                $td5.html($now.getFullYear() + '-' + $month + '-' + $day + ' ' + $hours + ':' + $minitues + ':' + $second)
            },
            onDeleted: function ($result, $obj) {
                del_all($($obj))
            },
            onSelectAll: function () {
                $('.royui_checkbox').each(function () {
                    if ($(this).prop('checked')) {
                        console.log($(this).val())
                    }
                })
            }
        })

        function del_all($obj) {
            let $code = $obj.data('code');
            let $ptr = $('#treeTable').find('tr[data-pid=' + $code + ']');
            if ($ptr.length > 0) {
                $($ptr).each(function ($i, $v) {
                    del_all($($v).find('td[data-code]'))
                })
                $($ptr).remove()
            }
            $obj.parents('tr').remove().remove()
        }

        $('#add').click(function () {
            add()
        })
        let $body = $('body')
        $body.on('click', '.add', function () {
            let $code = $(this).data('code')
            add($code, $(this))
        })
        let $open = null;

        function add($code = '0', $obj = null) {
            $open = layer.open({
                type: 2,
                title: '添加区划',
                content: '/district/add?code=' + $code,
                area: ['500px', '600px'],
                closeBtn: 2,
                btn: ['确定', '取消'],
                yes: function ($index, $layero) {
                    let $body = $layero.find('iframe').contents().find('body');
                    let $param = decodeURIComponent($($body).find('form').serialize());
                    $param = $param.split('&');
                    let $params = {};
                    $($param).each(function ($n, $obj) {
                        $params[$obj.split('=')[0]] = $obj.split('=')[1];
                    });
                    $.ajax({
                        type: 'post', dataType: 'json', cache: false,
                        url: '/district/add',
                        data: $params,
                        success: function ($data) {
                            if ($data['code'] === 200) {
                                layer.msg($data.message, {icon: 1, time: 1200}, function () {
                                    layer.close($open);
                                    if ($obj !== null) {
                                        let $level = $params['level']
                                        let $level_txt = ''
                                        if ($level === 4) {
                                            $level_txt = '乡级'
                                        } else if ($level === 3) {
                                            $level_txt = '县级'
                                        } else if ($level === 2) {
                                            $level_txt = '地级'
                                        } else if ($level === 1) {
                                            $level_txt = '省级'
                                        }
                                        let $now = new Date();
                                        let $nowdatetime = $now.getFullYear() + '-' + ($now.getMonth() + 1) + '-' + $now.getDate() + ' ' + $now.getHours() + ':' + $now.getMinutes() + ':' + $now.getSeconds()
                                        let $str = '<tr data-pid="' + $code + '">' +
                                                '<td style="text-align:center"><input type="checkbox" class="royui_checkbox" value="' + $params['code'] + '"></td>' +
                                                '<td style="width: 300px;text-indent:24px;"><span>' + $params['name'] + '</span></td>' +
                                                '<td style="width: 200px"><span>' + $params['code'] + '</span></td>' +
                                                '<td><span>' + $level_txt + '</span></td>' +
                                                '<td><span>' + $nowdatetime + '</span></td>' +
                                                '<td><span>0</span></td>' +
                                                '<td><span>' + (parseInt($params['status']) === 1 ? '正常' : '撤销') + '</span></td>' +
                                                '<td><a href="javascript:;" data-url="/district/edit?code=' + $params['code'] + '" data-code="' + $params['code'] + '" data-area="560px,750px" onclick="new royui().clickA(this,\'' + $params['code'] + '\',\'编辑\')" class="royui-button-a">编辑</a> &nbsp; <a href="javascript:;" data-url="{:url(\'del\')}?code=' + $params['code'] + '" data-code="' + $params['code'] + '" data-area="560px,750px" onclick="new royui().clickA(this,\'' + $params['code'] + '\',\'删除\')" class="royui-button-a">删除</a>' + ($level < 4 ? ' &nbsp; <a href="javascript:;" class="royui-button-a add" data-code="110106">添加下级区划</a>' : '') + '</td>' +
                                                '</tr>';
                                        $obj.parents('tr').after($str)
                                    } else {
                                        window.location.reload();
                                    }
                                });
                            } else {
                                layer.msg($data.message, {icon: 5});
                            }
                        }
                    })
                }
            })
        }

        $body.on('click', 'a[data-action]', function () {
            let $action = $(this).data('action'), $id = $(this).data('id');
            let $ids = [];
            if ($action === 'del' || $action === 'disable' || $action === 'enable' || $action === 'mip' || $action === 'nip') {
                $ids = [$id];
            } else if ($action === 'delAll' || $action === 'disableAll' || $action === 'enableAll' || $action === 'mipAll' || $action === 'nipAll') {
                $('.royui_checkbox').each(function () {
                    if ($(this).is(':checked')) {
                        $ids.push($(this).val())
                    }
                });
            }
            operate($ids, $action)
        })

        function operate($ids, $type) {
            let $msg = '', $tip = '';
            if ($type === 'del' || $type === 'delAll') {
                $msg = '确实要删除吗？';
                $tip = '删除'
            } else if ($type === 'disable' || $type === 'disableAll') {
                $msg = '确实要禁用吗？';
                $tip = '禁用'
            } else if ($type === 'enable' || $type === 'enableAll') {
                $msg = '确实要启用吗？';
                $tip = '启用'
            }
            if ($ids.length === 0) {
                layer.msg('请选择要' + $tip + '的项');
                return false
            }
            layer.confirm($msg, {icon: 3}, function () {
                $.ajax({
                    type: 'post', cache: false, dataType: 'json',
                    url: '/district/operate',
                    data: {'ids': $ids, 'type': $type},
                    beforeSend: function () {
                        layer.load(2, {shade: [0.3, '#fff']})
                    },
                    success: function (data) {
                        layer.closeAll('loading')
                        if (data.code === 200) {
                            layer.msg(data.message, {icon: 1, time: 1000}, function () {
                                location.reload()
                            });
                        } else {
                            layer.msg(data.message, {icon: 5})
                        }
                    }
                })
            })
        }
    });
</script>
</html>
